Search a 2D Matrix
Question
How can I efficiently search for a given value in a 2D matrix of integers?
Example 1
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Solution
- ▭
- ▯
all//Search a 2D Matrix.py
def searchMatrix(matrix, target):
if len(matrix) == 0 or len(matrix[0]) == 0:
return False
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False
all//Search a 2D Matrix.py
def searchMatrix(matrix, target):
if len(matrix) == 0 or len(matrix[0]) == 0:
return False
row = 0
col = len(matrix[0]) - 1
while row < len(matrix) and col >= 0:
if matrix[row][col] == target:
return True
elif matrix[row][col] > target:
col -= 1
else:
row += 1
return False